const db = require('../libs/db')
const Pagination = require('../libs/pagination')
const Log = db.model('log')
const User = db.model('user')

exports.logList = async ctx => {
  var oper = await ctx.user()
  var {uids, limit, page, show, user, created, updated, keyword, startDate, endDate} = ctx.query
  var order = [
  ]
  if (created) {
    order.push(['createdAt', created === 'desc' ? 'DESC' : 'ASC'])
  } else {
    order.push(['createdAt', 'DESC'])
  }
  if (updated) {
    order.push(['updatedAt', updated === 'desc' ? 'DESC' : 'ASC'])
  }
  var include = []
  if (user) {
    include.push({
      model: User,
      as: 'oper',
      attributes: ['id', 'name', 'nickName', 'avator', 'code', 'type', 'status']
    })
  }
  var where = {}
  // 管理员
  if (oper.type !== 1000) {
    where.uid = oper.id
    where.show = 1
  } else {
    if (uids) {
      where.uid = {$in: uids.split(',')}
    }
    if (typeof show !== 'undefined') {
      where.show = show
    }
  }
  if (startDate) {
    where.createdAt = {
      $between: [startDate, endDate]
    }
  }
  if (keyword) {
    keyword = '%' + keyword + '%'
    where.$or = [
      {action: {$like: keyword}},
      {desctiption: {$like: keyword}},
      {result: {$like: keyword}}
    ]
  }
  limit = parseInt(limit || 10)
  page = page || 1
  var count = await Log.count({where})
  var pages = new Pagination(count, limit)
  var offset = pages.sql(page).offset
  var result = await Log.findAll({where, include, order, offset, limit})

  ctx.body = {
    bool: true,
    msg: '',
    result,
    pages
  }
}

exports.delLog = async ctx => {
  var oper = await ctx.user()
  var {id} = ctx.query
  if (!id) {
    return ctx.body = {
      bool: false,
      msg: 'id参数不能为空'
    }
  }
  var log = await Log.findOne({where: {id}})
  if (!log) {
    return ctx.body = {
      bool: false,
      msg: '日志不存在'
    }
  }
  if (oper.type !== 1000) {
    if (log.uid !== oper.id) {
      return ctx.body = {
        bool: false,
        msg: '你无权删除此日志'
      }
    } else {
      // 代理自己删除日志并非删除
      log.show = 0
      await log.save()
      return ctx.body = {
        bool: true,
        msg: '删除成功'
      }
    }
  }
  await log.destroy()
  ctx.body = {
    bool: true,
    msg: '删除成功'
  }
}

